---@class UGCGameState_C:BP_UGCGameState_C
--Edit Below--

require("Script.GameConfigs.GlobalConfigs");
require("Script.GameConfigs.EventDefine");
require("Script.Common.UGCEventSystem");
require("Script.GameConfigs.Mode");
require("Script.GameConfigs.UIManager");
require("Script.Common.VectorHelper");
UGCGameSystem.UGCRequire('Script.Common.ue_enum_custom')
require("Script.Common.Debug")
require("Script.Common.RepHelper")
local UGCGameState = {
    --准备阶段剩余时间
    PrepareStageRemainTime = 10;
    --调整卡牌剩余时间
    AdjustRemainTime = 100;
    --玩家数量
    PlayerNum = 2; --调试的时候用2，实际为4
    --所有玩家的信息
    PlayerInfos = {};
    --目前的游戏状态
    CurrentGamestate = 0;
    --所有卡牌的列表
    CardList = { 1, 1, 2, 3, 4, 5 }; --调试用
    --目前回合的玩家标识
    CurRoundTeamIndex = 0;
    --目前回合的状态
    CurRoundStatus = 0;
    --目前回合的剩余时间
    CurRoundRemainTime = 0;
    -- [C]客户端玩家面板
    PlayerPanelDatas = {};
    -- 当前回合的玩家是否可以再打一次卡牌（打出迅捷行动）
    CanPlayerStartAnotherRound = false;

    TileList = {};

    MoveDir = 0;
    targetTile = nil;

    -- 选择卡牌后可以走到的tile的集合
    CanAchieveTiles = {};
};

function UGCGameState:GetReplicatedProperties()
    return "PrepareStageRemainTime",
        "CurRoundRemainTime",
        "AdjustRemainTime",
        "PlayerInfos",
        "CurRoundTeamIndex",
        "CurRoundStatus",
        "CurrentGamestate",
        "CanAchieveTiles",
        "TileList"
end

--√
function UGCGameState:ReceiveBeginPlay()
    print("UGCGameState:ReceiveBeginPlay")

    if self:HasAuthority() == true then
        print("hereh iss")
        for TeamIndex = 1, 4 do
            --这里不注释，向下不能运行
            --self.AutoPlayTotalTime[TeamIndex] = 0
        end
    else
        -- 客户端初始化UI
        -- AeroplaneChessUIManager:Init()
        UIManager:Init()
        local HeightUI = UE.LoadClass(UGCMapInfoLib.GetRootLongPackagePath() .. "Asset/UI/HeightControl.HeightControl_C");
        local PlayerController = GameplayStatics.GetPlayerController(self, 0);
        local MainUI_BP = WidgetBlueprintLibrary.Create(PlayerController, HeightUI, PlayerController);
        MainUI_BP:AddToViewport();
        -- 预加载粒子效果
        -- UGCParticleTools:PreLoad() --报错
    end

    -- 对于客户端，PlayerInfos的Onrep可能早于此处调用，此时不能再用初始数据覆盖
    if #self.PlayerInfos ~= 4 then
        -- 初始化四个位置的信息√
        for TeamIndex = 1, 4 do
            self.PlayerInfos[TeamIndex] = {
                PlayerKey = nil; -- 对应的玩家
                PlayerPawn = nil; -- 玩家的pawn
                CardInfos = { 1, 1, 2, 3, 4, 5 }; --持有卡牌的Pawn
                CardNum = self.PlayerNum;
                HasFinishedAdjustCard = false; --是否完成了调整卡牌，未使用
                -- 结算相关
                UID = nil;
                PlayerName = nil;
                Gender = nil;
                EndGame = false;
                EliminateNum = 0;
                CompletionTime = 9999;
                InWatching = false; -- 是否处于观战

                CardChoosed = 1; -- 玩家点击的卡牌,测试时先写1,TODO 卡牌点击做好以后要改
                TileChoosed = nil; -- 玩家选择要到达的砖块
                TileWaitForDelete = {};--待删除的砖块，也即物体移动过的砖块

                -- 选择卡牌后可以走到的tile的集合
                --CanAchieveTiles = {};
            }
            print("UGCGameState:ReceiveBeginPlay  playerinfos ")
        end
        self:FindAllAeroplanePawn() -- 分配pawn给玩家
    end
    --不注释无法向下运行
    self:FindAllTiles()
    print("finish init here")
    --self:FindAllHelicopters()
    --UGCBGMTools:Init()

end

-- (DS)将所有玩家的视角聚焦于顶部摄像机
function UGCGameState:SetAllPlayerFocusToTopCamera()
    print("UGCGameState:SetAllPlayerFocusToTopCamera")
    local PlayerControllerList = UGCGameSystem.GetAllPlayerController()
    for _, PlayerController in ipairs(PlayerControllerList) do
        if PlayerController then
            -- 所有playercontroller执行clint函数将视角拉到TopCamera
            --该函数位于playercontroller中
            UnrealNetwork.CallUnrealRPC(PlayerController, PlayerController, "ClientRPC_FocusCameraToTop", nil)
        end
    end
end

--获取玩家pawn√
function UGCGameState:FindAllAeroplanePawn()
    print("Chris : UGCGameState:FindAllAeroplanePawn")
    local classPath = UGCMapInfoLib.GetRootLongPackagePath() .. "Asset/Blueprint/BP_Player.BP_Player_C"
    local actorClass = UE.LoadClass(classPath)
    if actorClass then
        local actorList = GameplayStatics.GetAllActorsOfClass(self, actorClass, {})
        if actorList ~= nil and #actorList > 0 then
            print("actorList num is "..#actorList)
            for _, actor in pairs(actorList) do
                --if Mode.IsTeamIndexValid(actor.TeamIndex) then
                self.PlayerInfos[actor.TeamIndex].PlayerPawn = actor
                
                if self:HasAuthority() == true then
                    -- 初始化棋子状态
                    --actor.CurrentState = EPlaneState.AtHome
                end
                --end
            end
        end
        print("finished FindAllAeroplanePawn")
    end
end


-- 为玩家分配位置√
function UGCGameState:DisTributeTeamForPlayer(PlayerState)
    if PlayerState.TeamIndex ~= 0 then return end
    -- 随机找一个未占用的位置
    local availableTeamIndex = {}
    for TeamIndex = 1, 4 do
        --√
        if self.PlayerInfos[TeamIndex].PlayerKey == nil and self.PlayerInfos[TeamIndex].PlayerPawn~=nil then
            table.insert(availableTeamIndex, TeamIndex)
        end
    end
    if #availableTeamIndex <= 0 then return end
    local teamIndex = availableTeamIndex[math.random(#availableTeamIndex)]

    local PlayerInfo = self.PlayerInfos[teamIndex]
    -- 找第一个未分配过的位置分配，将playerinfos数组中分量i的属性设置为玩家的属性
    if PlayerInfo.PlayerKey == nil then
        print(string.format("UGCGameState:DisTributeTeamForPlayer:Player[%d] -> TeamIndex[%d]", PlayerState.PlayerKey,
            teamIndex))
        PlayerInfo.PlayerKey = PlayerState.PlayerKey
        PlayerState.TeamIndex = teamIndex
        print("PlayerInfo.PlayerPawn.TeamIndex"..PlayerInfo.PlayerPawn.TeamIndex)
        --保证playerinfo和playerpawn的TeamIndex一致
        PlayerInfo.PlayerPawn.TeamIndex = teamIndex
        print(string.format("playercardnum[%d]", PlayerInfo.CardNum)) --2
        print(string.format("playercardlist[%d]", #self.CardList))--6
        --初始化玩家所持有卡牌,暂时不做
        --[[
        for j = 1, PlayerInfo.CardNum do
            local RandomCard = math.random(1, #self.CardList)
            print(string.format("RandomCard[%d]", RandomCard))
            table.insert(PlayerInfo.CardInfos, RandomCard)
            print(string.format("PlayerInfo.CardInfos[%d]", PlayerInfo.CardInfos[j]))
        end
        ]]--
        -- 结算相关数据，暂时不考虑
        local PlayerAccountInfo = UGCPlayerStateSystem.GetPlayerAccountInfo(PlayerState.PlayerKey):Copy();
        PlayerInfo.UID = PlayerState.UID;
        PlayerInfo.PlayerName = PlayerState.PlayerName;
        PlayerInfo.Gender = PlayerAccountInfo.PlatformGender;
        PlayerInfo.IconURL = PlayerState.IconURL;
        PlayerInfo.PlayerLevel = PlayerState.PlayerLevel;
        PlayerInfo.FrameLevel = PlayerState.SegmentLevel;
    end
    print("success to DisTributeTeamForPlayer")
end

-- （DS）玩家选择卡牌
function UGCGameState:SelectCard(CardInfo)
    Debug:Log("UGCGameState:SelectCard   " .. CardInfo)

    if self.CurRoundStatus ~= ERoundStatus.WaitForSelectCard then return end
    --
    --选择完后关闭“选择卡牌提示”
    --UnrealNetwork.CallUnrealRPC_Multicast(UGCGameSystem.GameState, "Multicast_ShowSelectCardTips", false);
    -- UI获取玩家选择的卡牌，客户端发送参数给服务端，或者以参数的形式传递？？
    -- 回合进入打出卡牌动画中状态
    self.CurRoundStatus = ERoundStatus.PlayCard
    --同步运动是否可解决
    -- 关闭客户端的选择卡牌提示，后续加上动画播放
    UnrealNetwork.CallUnrealRPC_Multicast(self, "Multicast_PlayCard", self.CurRoundTeamIndex, CardInfo);
    -- 标记，卡牌为迅捷行动 则回合结束后再进行一次,只能进行一次
    --[[
    if CardInfo.IsXunJie and not self.CanPlayerStartAnotherRound then
        self.CanPlayerStartAnotherRound = true
    end
    ]] --

    -- 等待打出卡牌的动画，简化成桌面出现卡牌即可
    -- 桌面也不用出现卡牌了，就在右侧显示就好了
    print("UGCGameState:SelectCard prepare to call DoCardFunction")

    if self.CurRoundStatus == ERoundStatus.PlayCard then
        -- 回合进入进行卡牌功能状态
        self.CurRoundStatus = ERoundStatus.DoCardFunction
        self:DoCardFunction(CardInfo)
        print("UGCGameState:SelectCard call DoCardFunction")
    end
    -- 不知道怎么用的委托
    -- local PlayCardTimerDelegate = ObjectExtend.CreateDelegate(self,
    --     function()
    --         if self.CurRoundStatus == ERoundStatus.PlayCard then
    --             -- 回合进入进行卡牌功能状态
    --             self.CurRoundStatus = ERoundStatus.DoCardFunction
    --             self:DoCardFunction(CardInfo)
    --             Debug:Log("UGCGameState:SelectCard call DoCardFunction")
    --             print("UGCGameState:SelectCard call DoCardFunction")
    --         end
    --     end
    -- )
    --动画待补充
    --KismetSystemLibrary.K2_SetTimerDelegateForLua(PlayCardTimerDelegate, self, AeroplaneChessAnimationConfigs.PlayCardTime, false)

end

function UGCGameState:DoCardFunction(CardInfo)
    if self.CurRoundStatus ~= ERoundStatus.DoCardFunction then return end
    -- 获取脚下地砖
    local curPlayer = self.PlayerInfos[self.CurRoundTeamIndex].PlayerPawn
    if curPlayer==nil then
        Debug:Log("UGCGameState:DoCardFunction get nil playerpawn")
        return
    end
 
    Debug:Log("UGCGameState:DoCardFunction get playerpawn")
    local curTileIndex = curPlayer.CurrentTileIndex;
    print("curTileIndex is"..curTileIndex)
    -- 根据卡牌类型,执行相关操作
    local CanAchieveTiles = {}
    local CardControl = require("Script.Blueprint.CardControl")
    Debug:Log("UGCGameState:DoCardFunction get playerpawn")
    
    if CardInfo == ECardType.Queen then

        CanAchieveTiles = CardControl:QueenCanMoveTo(self.TileList[curTileIndex]);
        print("UGCGameState:DoCardFunction call CardControl:QueenCanMoveTo")
        print("ECardType.Queen CanAchieveTiles"..#CanAchieveTiles)
        Debug:Log("UGCGameState:DoCardFunction call CardControl:QueenCanMoveToend", CanAchieveTiles)

    elseif CardInfo == ECardType.HengCar then
        CanAchieveTiles = CardControl:HengCarCanMoveTo(self.TileList[curTileIndex]);
        print("UGCGameState:DoCardFunction call CardControl:HengCarCanMoveTo. Left and Right",CanAchieveTiles)
        

    elseif CardInfo == ECardType.PieCar then
        CanAchieveTiles = CardControl:PieCarCanMoveTo(self.TileList[curTileIndex]);
        print("UGCGameState:DoCardFunction call CardControl:PieCarCanMoveTo")

    elseif CardInfo == ECardType.NaCar then
        CanAchieveTiles = CardControl:NaCarCanMoveTo(self.TileList[curTileIndex]);
        print("UGCGameState:DoCardFunction call CardControl:NaCarCanMoveTo")

    elseif CardInfo == ECardType.Knight then
        CanAchieveTiles = CardControl:KnightCanMoveTo(self.TileList[curTileIndex]);
        print("UGCGameState:DoCardFunction call CardControl:KnightCanMoveTo")

        -- ...每个卡牌对应一个功能函数，同时UI需广播至所有客户端
    end

    -- 高亮所有可以到达的地砖，没实现
    -- for index, value in ipairs(CanAchieveTiles) do
    --     --Debug:Log("SetTileHighlight",KismetSystemLibrary.GetDisplayName(self.TileList[CanAchieveTiles[index]]))
    --     --self.TileList[CanAchieveTiles[index]]:SetTileHighlight(true);-- nil
    --     CanAchieveTiles[index]:SetTileHighlight(true);
    --     Debug:Log("UGCGameState:DoCardFunction SetTileHighlight",KismetSystemLibrary.GetDisplayName(self.TileList[CanAchieveTiles[index]]))
    -- end

    -- 更新能到达的位置
    -- TODO: 回合结束后要重新设置为{},并且取消高亮
    -- local playerinfo = self.PlayerInfos[CurRoundTeamIndex]
    -- local tiles = playerinfo.CanAchieveTiles ;
    self.CanAchieveTiles = CanAchieveTiles
    --UGCEventSystem:SendEvent(EventType.CanAchieveTiles, self.CanAchieveTiles,true);
    Debug:Log("UGCGameState:DoCardFunction call CardControlhhh", self.CanAchieveTiles)

    --格子破裂、玩家坠落  不应该在这里

    --通知客户端棋子开始移动,从卡牌功能获取移动
    --AIController:MoveNumSteps(step)

    -- local PlayerKey = self.PlayerInfos[self.CurRoundTeamIndex].PlayerKey
    -- local PlayerController = UGCGameSystem.GetPlayerControllerByPlayerKey(PlayerKey)
    --UnrealNetwork.CallUnrealRPC(PlayerController, PlayerController, "ClientRPC_StartPlaneSelection", CanChoosePlaneIndex)

    -- 当打出迅捷行动，通知客户端再次选择卡牌，待完善！！！！！！！！！！
    -- if self.CanPlayerStartAnotherRound then
    --     UnrealNetwork.CallUnrealRPC(PlayerController, PlayerController, "ClientRPC_SelectCardAgain", AtHomeNum, false);
    -- else
    --     --实际上，应该是完成移动后执行此部分代码，和飞行棋类似，Update判断到达指定位置后执行下面逻辑！！！！！
    --     --self.CurRoundStatus = ERoundStatus.AddCard
    --     --self:AddCard(self.PlayerInfos[self.CurRoundTeamIndex])
    -- end
end

-- (C)是在客户端执行的！！！,所以需同步变量
-- 检测是否点击的砖块是否能到达
function UGCGameState:CheckIsTileAchieved(Tile)
    Debug:Log("UGCGameState:CheckIsTileAchieved", Tile)
    Debug:Log("UGCGameState:CheckIsTileAchieved2", self.CanAchieveTiles)
    print("CheckIsTileAchieved is right")
    print("self.CanAchieveTiles Num"..#self.CanAchieveTiles)
    for index, value in ipairs(self.CanAchieveTiles) do
        if value~=0 and Tile == self.TileList[self.CanAchieveTiles[index].ID] then

            UGCEventSystem:SendEvent(EventType.CanAchieveTiles, self.CanAchieveTiles,false);
            self.CanAchieveTiles = {0,0,0,0,0,0};
            print("had choosed canachievetiles!")
            return index
        end
    end
    return -1
end

-- (DS)执行移动player
function UGCGameState:DoMovePlayer(direction, targetTile)
    print("UGCGameState:DoMovePlayer")
    -- test
    --self:PlayerFinishedMove();

    -- 通知客户端棋子开始移动
    --UnrealNetwork.CallUnrealRPC_Multicast(self, "Multicast_PlayerMove", self.CurRoundTeamIndex, PlaneIndex, self.CurRoundDiceResult);
    UnrealNetwork.CallUnrealRPC_Multicast(self, "Multicast_ShowRemainTimeTips", false);
    print("DoMovePlayer is success here")
    --执行移动逻辑
    local playerpawn = self:GetCurRoundPlayerInfo().PlayerPawn
    local AIController = playerpawn:GetController()
    if AIController == nil then
        print('ERROR: UGCGameState:DoMovePlayer AIController is nil ')
        return
    end
    print("DoMovePlayer directionaa"..direction)
    AIController:MoveTargetTile(direction,targetTile)

    -- TODO:暂时删除砖块写在移动中了，如果不行再考虑在此处处理TileList，所有destroyed的砖块全部碎裂，并且从list里删除，


end

function UGCGameState:PlayerFinishedMove()
    Debug:Log("UGCGameState:PlayerFinishedMove")
    print("UGCGameState:PlayerFinishedMove")
    self.CurRoundStatus = ERoundStatus.RoundEnd
    --self.PlayerInfos[self.CurRoundTeamIndex].EndGame = true;

    LuaQuickFireEvent("PlayerRoundEnd", self)
end

-- 再次执行的问题?
function UGCGameState:AddCard(PlayerInfo)
    if self.CurRoundStatus ~= ERoundStatus.AddCard then return end
    local CardNumNeed = self.CardNum - #self.CardInfos
    for i = 1, CardNumNeed do
        local RandomCard = math.random(1, #self.CardList)
        table.insert(PlayerInfo.CardInfos, RandomCard)
    end
    -- UI刷新卡牌数量显示，还是说以传递数量参数的形式？函数需改变
    --UnrealNetwork.CallUnrealRPC_Multicast(UGCGameSystem.GameState, "Multicast_PlayerCardUI",UGCGameSystem.GameState.PlayerInfos);
    -- 不是上面，而是这个函数更新卡牌
    UnrealNetwork.CallUnrealRPC_Multicast(UGCGameSystem.GameState, "Multicast_PlayerPanel", UGCGameSystem.GameState.PlayerInfos);

    self.CurRoundStatus = ERoundStatus.RoundEnd
    LuaQuickFireEvent("PlayerRoundEnd", self)
end

-- (DS)调整卡牌,adjustcardlist为点击卡牌获得的参数，是客户端点击card后，发送到服务端执行这个函数，在服务端更改相关数据，再到客户端更新UI。
function UGCGameState:RemoveAndAddCard(AdjustCardList)
    local PlayerController = GameplayStatics.GetPlayerController(UGCGameSystem.GameState, 0);
    local TeamIndex = PlayerController.PlayerState.TeamIndex;
    --remove
    if PlayerController ~= nil then
        for i = 1, #AdjustCardList do
            local AdjustCardIndex = AdjustCardList[i]
            table.remove(self.PlayerInfos[TeamIndex].CardInfos, AdjustCardIndex)
        end
    end
    --add
    if PlayerController ~= nil then
        local CardNumNeed = self.CardNum - #self.CardInfos
        for i = 1, CardNumNeed do
            local RandomCard = math.random(1, #self.CardList)
            table.insert(self.PlayerInfos[TeamIndex].CardInfos, RandomCard)
        end
    end
    self.PlayerInfos[TeamIndex].HasFinishedAdjustCard = true;
end

--√成功
function UGCGameState:FindAllTiles()
    print("Chris : UGCGameState:FindAllTills")
    local classPath = UGCMapInfoLib.GetRootLongPackagePath() .. "Asset/Blueprint/BP_Tile.BP_Tile_C"
    local actorClass = UE.LoadClass(classPath)
    -- 四维数组, 分别对应level ,x+8,y+8,z+8. (+7是为了解决下标为-的问题)
    local tileMap = {}
    for x = 1, 15 do
        tileMap[x] = {}
        for y = 1, 15 do
            tileMap[x][y] = {}
            for z = 1, 3 do
                tileMap[x][y][z] = nil
            end
        end
    end
    if actorClass then
        print("sdfkgjosjo")
        local actorList = GameplayStatics.GetAllActorsOfClass(self, actorClass, {})
        print("sdjfjslgj")
        print(string.format("actorclassnum[%d]", #actorList)) --279
        for i = 1, #actorList do
            self.TileList[i] = actorList[i]
            actorList[i].ID = i
            print("asdfadsa")
            --print("cjjjjjjjjjj"..self.TileList[i]..actorList[i].ID)
            local str = KismetSystemLibrary.GetDisplayName(actorList[i]);
            local pos = RepHelper:StrToPos(str)
            if #pos ~= 3 then

                Debug:Log("ToPosFailed", str, pos)
            end
            if #pos == 3 then
                tileMap[pos[1] + 8][pos[2] + 8][pos[3]] = actorList[i]
            end
            --print("acjiiiii"..self.TileList[i]..actorList[i].ID)
        end
        print("find all tile !")
       -- print(string.format("tileidsdfsfsdfs[%d]", self.TileList[5].ID)) --5
    end

    Debug:Log("map get tile num", cnt)
    Debug:Log(self.TileList);
    local cnt = 0;
    for x = 1, 15 do
        for y = 1, 15 do
            for z = 1, 3 do
                if tileMap[x][y][z] ~= nil then
                    cnt = cnt + 1
                    UGCGameState:BindTile(x, y, z, tileMap)
                    
                end
            end
        end
    end

    
end

function UGCGameState:BindTile(x, y, z, tileMap)
    local tile = tileMap[x][y][z]
    for i = 1, 6 do
        local xx = x + EDirectionX[i]
        local yy = y + EDirectionY[i]
        if i == 1 then
            tile.LeftUp = tileMap[xx][yy][z]
        elseif i == 2 then
            tile.Left = tileMap[xx][yy][z]
        elseif i == 3 then
            tile.LeftDown = tileMap[xx][yy][z]
        elseif i == 4 then
            tile.RightUp = tileMap[xx][yy][z]
        elseif i == 5 then
            tile.Right = tileMap[xx][yy][z]
        elseif i == 6 then
            tile.RightDown = tileMap[xx][yy][z]
        end
    end
    if self.Left ~= nil then

        self.Left.OnActorHit:Add(self.Left_OnActorHit, self)
        Debug:Log("BP_Tile:ReceiveBeginPlay");
        self.MiddleLocation = self:K2_GetActorLocation()
    end
end

function UGCGameState:HasTeamFinishedGame(TeamIndex)
    return self.PlayerInfos[TeamIndex].EndGame
end


--[[------------------------------------------Getter------------------------------------------------------]] --
-- (DS)返回目标砖块已有玩家Pawn
function UGCGameState:GetTileStandPawnList(TargetTileIndex)
    local Tile = self.TileList[TargetTileIndex];
    local PawnList = Tile:GetPlayerOnThisTile();
    print(string.format("UGCGameState:GetTileStandPawnList:TargetTileIndex[%s] PawnNum[%s]", tostring(TargetTileIndex),
        tostring(#PawnList)))
    return PawnList;
end

function UGCGameState:GetCurRoundPlayerInfo()
    return self.PlayerInfos[self.CurRoundTeamIndex];
end

-- （Ds）将目标砖块的pawn移动到对应位置，给将要到来的Pawn留出最后一个空位置
--[[
function UGCGameState:MakeTileHaveEmptySlot(Tile,PawnList)
    -- 砖块上原本有多少玩家
    local PawnNum = #PawnList;
    print("UGCGameState:MakeTileHaveEmptySlot,PawnNum is ".. tostring(PawnNum))
    if PawnNum == 1 then
        PawnList[1]:PawnMoveToLocation(Tile:GetTwoPlayerTileLocation(1));
    elseif PawnNum == 2 then
        PawnList[1]:PawnMoveToLocation(Tile:GetThreePlayerTileLocation(1));
        PawnList[2]:PawnMoveToLocation(Tile:GetThreePlayerTileLocation(2));
    elseif PawnNum == 3 then
        PawnList[1]:PawnMoveToLocation(Tile:GetFourPlayerTileLocation(1));
        PawnList[2]:PawnMoveToLocation(Tile:GetFourPlayerTileLocation(2));
        PawnList[3]:PawnMoveToLocation(Tile:GetFourPlayerTileLocation(3));
    end
end
]] --

--[[
-- （Ds）将目标砖块上的玩家重置到对应位置
function UGCGameState:ResetTilePawn(TileIndex)
    print("UGCGameState:ResetTilePawn,TileIndex is ".. tostring(TileIndex))
    local PawnList = self:GetTileStandPawnList(TileIndex);
    local Tile = self.TileList[TileIndex];
    -- 砖块上有多少玩家
    local PawnNum = #PawnList;
    if PawnNum == 1 then
        PawnList[1]:PawnMoveToLocation(Tile:GetOnePlayerLocation());
    elseif PawnNum == 2 then
        PawnList[1]:PawnMoveToLocation(Tile:GetTwoPlayerTileLocation(1));
        PawnList[2]:PawnMoveToLocation(Tile:GetTwoPlayerTileLocation(2));
    elseif PawnNum == 3 then
        PawnList[1]:PawnMoveToLocation(Tile:GetThreePlayerTileLocation(1));
        PawnList[2]:PawnMoveToLocation(Tile:GetThreePlayerTileLocation(2));
        PawnList[3]:PawnMoveToLocation(Tile:GetThreePlayerTileLocation(3));
    elseif PawnNum == 4 then
        PawnList[1]:PawnMoveToLocation(Tile:GetFourPlayerTileLocation(1));
        PawnList[2]:PawnMoveToLocation(Tile:GetFourPlayerTileLocation(2));
        PawnList[3]:PawnMoveToLocation(Tile:GetFourPlayerTileLocation(3));
        PawnList[4]:PawnMoveToLocation(Tile:GetFourPlayerTileLocation(4));
    end
end
]] --


--[[------------------------------------------Checker------------------------------------------------------]] --
-- （DS、客户端）游戏是否结束（3个玩家结束游戏）
function UGCGameState:IsGameFinished()
    local FinishedPlayerNum = 0
    for TeamIndex = 1, 4 do
        if self:HasTeamFinishedGame(TeamIndex) then
            FinishedPlayerNum = FinishedPlayerNum + 1
        end
    end
    return FinishedPlayerNum >= 3
end

--[[------------------------------------------客户端接收到游戏状态数据更新------------------------------------------------------]] --

--[[function UGCGameState:OnRep_CurrentGamestate()
    print("UGCGameState:OnRep_CurrentGamestate,currentState is" .. tostring(self.CurrentGamestate));
    if self.CurrentGamestate == EGameStatus.WaitReady then
        local PlayerController = GameplayStatics.GetPlayerController(UGCGameSystem.GameState, 0);
        if PlayerController ~= nil then
            local PlayerState = PlayerController.PlayerState;
            if PlayerState ~= nil then
                PlayerState:TrySendTeamIndexAssignEvent();
            else
                print("UGCGameState:OnRep_CurrentGamestate PlayerState is nil ");
            end
        else
            print("UGCGameState:OnRep_CurrentGamestate PlayerController is nil ");
        end
    end
end
]] --

-- 执行的是这里
function UGCGameState:OnRep_CanAchieveTiles()
    print("UGCGameState:OnRep_CanAchieveTiles")
    Debug:Log("UGCGameState:OnRep_CanAchieveTiles iswhat",self.CanAchieveTiles)
    if self.CanAchieveTiles == {} then 
        UGCEventSystem:SendEvent(EventType.CanAchieveTiles, self.CanAchieveTiles,false);
    else
        UGCEventSystem:SendEvent(EventType.CanAchieveTiles, self.CanAchieveTiles,true);
    end
    
end

function UGCGameState:OnRep_PrepareStageRemainTime()
    print("UGCGameState:OnRep_PrepareStageRemainTime")
    UGCEventSystem:SendEvent(EventType.PrepareStageRemainTimeChanged, self.PrepareStageRemainTime);
end

function UGCGameState:OnRep_CurRoundRemainTime()
    UGCEventSystem:SendEvent(EventType.CurRoundRemainTimeChanged, self.CurRoundRemainTime);
end

-- 没执行
function UGCGameState:OnRep_AdjustRemainTime()
    print("UGCGameState:OnRep_AdjustRemainTime")
    ugcprint(string.format("UGCGameState:OnRep_AdjustRemainTime[%f]", self.AdjustRemainTime));
    UGCEventSystem:SendEvent(EventType.AdjustRemainTimeChanged, self.AdjustRemainTime);
end

function UGCGameState:OnRep_PlayerInfos()
    log_tree_dev("UGCGameState:OnRep_PlayerInfos", self.PlayerInfos);
    UGCEventSystem:SendEvent(EventType.PlayerInfosChanged, self.PlayerInfos);
end

function UGCGameState:OnRep_CurRoundStatus()
    ugcprint(string.format("UGCGameState:OnRep_CurRoundStatus[%d]", self.CurRoundStatus));
    UGCEventSystem:SendEvent(EventType.CurRoundStatusChanged, self.CurRoundStatus);
end

function UGCGameState:OnRep_CurRoundTeamIndex()
    ugcprint(string.format("UGCGameState:OnRep_CurRoundTeamIndex[%d]", self.CurRoundTeamIndex));
    UGCEventSystem:SendEvent(EventType.CurTeamIndexChanged, self.CurRoundTeamIndex);
end

--[[------------------------------------------广播给客户端的方法------------------------------------------------------]] --

-- 玩家数据同步到客户端
function UGCGameState:Multicast_PlayerPanel(PlayerInfos)
    print("UGCGameState:Multicast_PlayerPanel")
    self.PlayerPanelDatas = PlayerInfos
    UGCEventSystem:SendEvent(EventType.PlayerPanelChange, PlayerInfos);
end

-- 游戏开始提示
function UGCGameState:Multicast_ShowStartTips()
    UGCEventSystem:SendEvent(EventType.GameStartChanged);
end

-- 开启当前回合剩余时间提示
function UGCGameState:Multicast_ShowRemainTimeTips(IsShow)
    self.ShowRemainTime = IsShow;
end

-- 开始新回合
function UGCGameState:Multicast_NewRoundStart(TeamIndex, PlayerKey, IsPlayAnotherRound)
    UGCEventSystem:SendEvent(EventType.PlayerStartNewRound, TeamIndex, PlayerKey, IsPlayAnotherRound);
    UGCEventSystem:SendEvent(EventType.SelectCardUI, TeamIndex, PlayerKey);
end

-- 广播卡牌选择结果，后续可能加上动画，目前的作用仅为通知当前客户端关闭选择卡牌通知
function UGCGameState:Multicast_PlayCard(TeamIndex, CardInfo)
    UGCEventSystem:SendEvent(EventType.PlayCard, TeamIndex, CardInfo);
end

-- 玩家卡牌UI
--这个更新：UnrealNetwork.CallUnrealRPC_Multicast(UGCGameSystem.GameState, "Multicast_PlayerPanel", UGCGameSystem.GameState.PlayerInfos);
--function UGCGameState:Multicast_PlayerCardUI(PlayerInfos)
    --UGCEventSystem:SendEvent(EventType.UpdateCardUI, PlayerInfos)
--end

-- 玩家移动了棋子，客户端收到后播动画
function UGCGameState:Multicast_PlayerMove(TeamIndex, PlaneIndex, NumSteps)
    ugcprint(string.format("Multicast_PlayerMove: P[%d] Plane[%d] Step[%d]", TeamIndex, PlaneIndex, NumSteps));
    UGCEventSystem:SendEvent(EventType.PlayerFlyPlane, TeamIndex, PlaneIndex, NumSteps);
end

-- 显示玩家调整卡牌的UI
function UGCGameState:Multicast_AdjustCardUI()
    UGCEventSystem:SendEvent(EventType.AdjustCardUI);
end

--[[
-- Show select card tips UIBP_RoundOperation
function UGCGameState:Multicast_ShowSelectCardTips(isShow)
    
    UGCEventSystem:SendEvent(EventType.ShowSelectCardTips,isShow);
    
end

--Show Adjust Card tips
function UGCGameState:Multicast_ShowAdjustCardTips()
	-- body
    UGCEventSystem:SendEvent(EventType.ShowAdjustCardTips);
end

]]

return UGCGameState;
